package com.suppor.rpc.client;

import com.suppor.rpc.core.register.RegisterInfo;
import com.suppor.rpc.core.trans.RpcRequest;
import com.suppor.rpc.proto.codec.RpcDecoder;
import com.suppor.rpc.proto.codec.RpcEncoder;
import com.suppor.rpc.proto.handler.RpcResponseHandler;
import com.suppor.rpc.proto.protocol.RpcProtocol;
import com.suppor.rpc.register.RegisterService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * 发送请求,基于netty实现
 */
public class ClientSend {
    private static final Logger LOG = LoggerFactory.getLogger(ClientSend.class);
    private Bootstrap bootstrap;
    private static final EventLoopGroup group = new NioEventLoopGroup();

    public ClientSend() {
        this.bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new RpcEncoder());
                        channel.pipeline().addLast(new RpcDecoder());
                        channel.pipeline().addLast(new RpcResponseHandler());
                    }
                });
    }

    public void send(RpcProtocol<RpcRequest> protocol, RegisterService registerService) throws Exception {
        RpcRequest request = protocol.getBody();
        int hashCode = protocol.getHeader().getRequestId().hashCode();
        RegisterInfo registerInfo = registerService.discovery(request.getServiceImpl(), request.getServiceVersion(), hashCode);
        if (null == registerInfo) {
            throw new NullPointerException("Please Register Center");
        }
        ChannelFuture future = this.bootstrap.connect(new InetSocketAddress(registerInfo.getServerAddr(), registerInfo.getPort())).sync();
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    LOG.info("Connect Server {} Port {} Success. ", registerInfo.getServerAddr(), registerInfo.getPort());
                } else {
                    LOG.info("Connect Server {} Port {} Fail. ", registerInfo.getServerAddr(), registerInfo.getPort());
                    channelFuture.cause().printStackTrace();
                    group.shutdownGracefully();
                }
            }
        });
        // 发送
        future.channel().writeAndFlush(protocol);
    }
}
